package cn.longwingstech.intelligence.bibackend.mq.consumer;


import cn.hutool.json.JSONUtil;
import cn.longwingstech.intelligence.bibackend.ai.PromptTemplates;
import cn.longwingstech.intelligence.bibackend.ai.entity.GenResultEntity;
import cn.longwingstech.intelligence.bibackend.exception.ErrorCode;
import cn.longwingstech.intelligence.bibackend.exception.ThrowUtils;
import cn.longwingstech.intelligence.bibackend.model.entity.Chart;
import cn.longwingstech.intelligence.bibackend.model.enums.ChartStatus;
import cn.longwingstech.intelligence.bibackend.service.ChartService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.template.st.StTemplateRenderer;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.Map;

/**
 * rabbitmq 全局消费者
 */
@Slf4j
@Component
public class RabbitMQGlobalConsumer {
    @Resource
    private ChartService chartService;

    @Resource
    private ChatClient chatClient;
    @RabbitListener(queues = "genQueue")
    public void onGenQueueMessage(Message message, Channel channel) throws IOException {
        String messageBody = new String(message.getBody());
        Chart chart = JSONUtil.toBean(messageBody, Chart.class);
        String name = chart.getName();
        String goal = chart.getGoal();
        String chartData = chart.getChartData();
        String chartType = chart.getChartType();
        Long userId = chart.getUserId();
        PromptTemplate template = PromptTemplate.builder()
                .renderer(StTemplateRenderer.builder().startDelimiterToken('^').endDelimiterToken('^').build())
                .template(PromptTemplates.CHARTS_GEN)
                .build();
        String prompt = template.render(Map.of("name", name, "goal", goal, "chartData", chartData, "chartType", chartType));
        GenResultEntity entity = null;
        try {
            entity = chatClient.prompt(prompt).call().entity(GenResultEntity.class);
            //保存
            System.out.println(entity);
            Chart chartAsync = new Chart();
            chartAsync.setName(name);
            chartAsync.setGoal(goal);
            chartAsync.setChartData(chartData);
            chartAsync.setChartType(chartType);
            chartAsync.setGenChart(entity.getOption());
            chartAsync.setGenResult(entity.getResult());
            chartAsync.setUserId(userId);
            chartAsync.setStatus(ChartStatus.SUCCEED.getValue());
            chartAsync.setId(chart.getId());
            boolean result = chartService.updateById(chartAsync);
            ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR);
        } catch (Exception e) {
            handleChartUpdateError(chart.getId(), "AI 错误");
        }
    }
    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(ChartStatus.FAILED.getValue());
        updateChartResult.setExecMessage("execMessage");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }
}
